package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author lqw
 * @since 2022-06-20
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IApUserFollowService apUserFollowService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //核查前端传来的数据
        if (dto == null || (StringUtils.isEmpty(dto.getPhone())
                && StringUtils.isEmpty(dto.getPassword())
                && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 如果手机号和密码不为空,使用手机号和密码登录
        if (!StringUtils.isEmpty(dto.getPhone())
                && !StringUtils.isEmpty(dto.getPassword())) {
            //根据手机号拿到数据库的盐
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(query);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String salt = one.getSalt();
            String psd = dto.getPassword() + salt;
            String md5Psd = DigestUtils.md5DigestAsHex(psd.getBytes());
            if (!md5Psd.equals(one.getPassword())) {
                //密码不正确
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码正确,生成token返回给前端
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", one.getId());
            String token = AppJwtUtil.getToken(userInfo);
            //创建前端返回对象
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            return ResponseResult.okResult(result);
        }
        //如果版本号不为空,以游客身份浏览
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", 0);
            String token = AppJwtUtil.getToken(userInfo);
            //创建前端返回对象
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            return ResponseResult.okResult(result);
        }

        return null;
    }

    /**
     * 关注和取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //判断用户是否登录
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            //未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建关注对象
        ApUserFollow follow = new ApUserFollow();
        //填充数据
        follow.setUserId(user.getUserId());
        ApUser apUser = this.getById(user.getUserId());
        follow.setUserName(apUser.getName());
        //远程调用article微服务根据作者id查询出作者
        ResponseResult<ApAuthor> authorById = articleFeign.getAuthorById(dto.getAuthorId());
        ApAuthor author = authorById.getData();
        follow.setFollowId(author.getUserId());
        follow.setFollowName(author.getName());
        follow.setLevel(1);
        follow.setIsNotice(false);
        follow.setCreatedTime(new Date());
        //判断当前用户和当前作者有无关注记录
        LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
        query.eq(ApUserFollow::getUserId,user.getUserId())
                .eq(ApUserFollow::getFollowId,author.getUserId());
        ApUserFollow one = apUserFollowService.getOne(query);
        if (one == null){
            //没有关注记录
            if (dto.getOperation() == 0){
                //保存关注记录
                apUserFollowService.save(follow);
            }
        }else {
            if (dto.getOperation() == 1){
                //删除关注记录  这里的query和上面的一样
                apUserFollowService.remove(query);
            }
        }
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(author.getUserId());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setOperation(dto.getOperation());
        //kafka远程发送消息给用户行为微服务
        kafkaTemplate.send(followBehaviorTopic, JSON.toJSONString(followBehaviorDto));
        return ResponseResult.okResult();
    }
}
